<template>
  <div class="content">
    <div style="margin:10px;">
      <el-button type="primary" size="default" @click="backEvent">返回</el-button>
    </div>
    <el-card style="max-height: 550px;" :body-style="{ height:'450px', overflow:'auto' }">
      <template #header>
        <span>生产订单信息</span>
      </template>
      <Grid></Grid>
    </el-card>
    <el-card style="max-height: 500px;margin:10px 0;">
      <template #header>
        <span>设置质检单关联生产订单</span>
      </template>
      <el-form :model="form" label-width="auto" ref="ruleFormRef" :rules="rules" style="max-width: 600px">
        <el-form-item prop="productOrder" label="生产订单">
          <el-input v-model="form.productOrder" placeholder="请在上方卡片中选择一个订单"></el-input>
        </el-form-item>
        <span class="tip">质检单创建时间范围:{{ getTimeFrame() }}</span>
        <el-form-item prop="dateList" label="时间段选择">
          <el-time-picker v-model="form.dateList" is-range range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="HH:mm:ss"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="submitEvent">提交</el-button>
      </template>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
//@ts-ignore
import type { VbenFormProps } from "#/adapter/form";
import { useRouter,useRoute } from "vue-router";
import type { VxeGridProps, VxeGridListeners } from "#/adapter/vxe-table";
import { ElMessage,ElMessageBox,ElCard, ElInput,ElForm,ElFormItem, ElDialog,ElButton,ElLoading,ElTag,ElTimePicker} from "element-plus";
import { Button, Upload, RadioButton, RadioGroup } from "ant-design-vue";
import { useVbenVxeGrid } from "#/adapter/vxe-table";
import { useVbenForm } from '#/adapter/form';
import { Page } from "@vben/common-ui";
import { $t } from "#/locales";
import { nextTick, ref, onUnmounted, onMounted,reactive } from "vue";
import { useVbenModal, VbenButton } from "@vben/common-ui";
//@ts-ignore
import {  reqProductOrderList, reqUpdateQuality } from "#/api/qualityTesting/index.ts";
import dayjs from "dayjs";
//@ts-ignore
import { dealVxeGridFilterParameter } from "#/utils/tools.ts";
const router = useRouter(),route = useRoute();


const routeQuery:any = reactive({
  dateTime:"",
  initQueryDateTime:""
})

onMounted(() => {
  routeQuery.dateTime = route.query.dateTime;
  routeQuery.initQueryDateTime = dayjs(routeQuery.dateTime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
  const tarColumn = gridOptions.value.columns.find(column => column.field === 'createTime');
  if (tarColumn && tarColumn.filters) {
    tarColumn.filters[0].data = routeQuery.initQueryDateTime;
  }
})

let tableFilterParameterObject = null;

const gridOptions: VxeGridProps = ref({
  columns: [
    { 
      type:'radio',
      title:'选择订单',
      width: 100
    },
    { title: "序号", type: "seq", width: 50 },
    {
      field: "productOrderNumber",
      title: "生产订单号",
      width: '',
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    {
      field: "code",
      title: "物料编码",
      width: ''
    },
    {
      field: "name",
      title: "物料名称",
      width: ''
    },
    {
      field: "stateName",
      title: "状态",
      width: ''
    },
    {
      field: "planQuantity",
      title: "计划数量",
      width: ''
    },
    {
      field: "createTime",
      title: "创建时间",
      width: '',
      filters:[{ data:"",checked:true }],
      filterRender:{ name:"customFilter",type:"date" }
    }
  ],
  toolbarConfig: {
    search: false,
    custom: true,
    export: false,
    refresh: true,
    zoom: true
  },
  filterConfig: {
    remote: true
  },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    pageSizes: [10, 20, 30, 50, 100]
  },
  height:"100%",
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query:({ page }, formValues) => proxyConfigQueryEvent({ page, formValues })
    }
  }
});

const gridEvents: VxeGridListeners = {
  filterChange({ filterList }) {
    tableFilterEvent(filterList);
  },
  radioChange: ({ row }) => {
    tableRadioChangeEvent(row);
  }
};

const proxyConfigQueryEvent = async (option:any) => {
  const { page,formValues } = option;
  let params:any = { page:page.currentPage,size:page.pageSize,createTime:routeQuery.initQueryDateTime };
  if(tableFilterParameterObject){
    Object.assign(params,tableFilterParameterObject);
  }
  try {
    const response = await reqProductOrderList(params);
    return {
      total: response.data.totalElements,
      items: response.data.content
    };
  } catch {
    return { items: [], total: 0 };
  }
}


const [Grid, gridApi] = useVbenVxeGrid({ formOptions: null, gridOptions: gridOptions, gridEvents: gridEvents });

const tableFilterEvent = (filterList:any) => {
  const parameter = dealVxeGridFilterParameter(filterList);
  tableFilterParameterObject = parameter;
  gridApi.query();
}
const tableRadioChangeEvent = (row:any) => {
  form.productOrder = row.productOrderNumber;
  selectedRow.value = row;
}


const selectedRow:any = ref(null);
 
const ruleFormRef:any = ref(null);

const form = reactive({
  productOrder:"",
  dateList:""
})

const submitEvent = () => {
  ruleFormRef.value.validate((valid) => {
    if(valid){
      ElMessageBox.confirm('确定将此时间段内的质检信息关联到此订单吗?','提示',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {
        updateQuality();
      })
    }
  })
}

const updateQuality = () => {
  const { productOrder,dateList } = form;
  const { dateTime } = routeQuery;
  const date = dayjs(dateTime).format('YYYY-MM-DD');
  const parameter = {
    productNumber:productOrder,
    startTime1: date + ' ' + dateList[0],
    endTime1: date + ' ' + dateList[1]
  }
  reqUpdateQuality(parameter).then(response => {
    if(response.code == 200){
      ElMessage.success("更新成功");
      setTimeout(() => { backEvent() }, 400);
    }
    console.log("更新质检列表信息api",response);
  },error => {
    ElMessage.error("更新失败,请重试");
    console.log("更新质检列表信息api",error);
  })
}

const validate1 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请在上方卡片中选择订单'));
  } else {
    selectedRow.value === null ? callback('请先在上方卡片中选择订单') :
    value == selectedRow.value.productOrderNumber ? callback() : callback('当前订单和卡片中选择的不一致');
  }
}
const validate2 = (rule: any, value: any, callback: any) => {
  if (!value || value === "" || value.length === 0) {
    callback(new Error('请选择时间段'));
  } else {
    callback()
  }
}
const rules = reactive({
  productOrder: [{ validator: validate1, trigger: 'change' }],
  dateList: [{ validator: validate2, trigger: 'change' }]
})

const backEvent = () => {
  router.back();
}

const getTimeFrame = () => {
  const { dateTime,initQueryDateTime} = routeQuery;
  const date = dayjs(initQueryDateTime).format('YYYY-MM-DD');
  const { dateList } = form;
  if(dateList && dateList.length === 2){
    return date + ' ' + dateList[0] + '-' + date + ' ' + dateList[1];
  }
  return date;
}
</script>

<style lang="scss" scoped>
.tip{
  font-size:12px;
  color:#9195a3;
}
</style>
